package com.hethongviet.vending.pages;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hethongviet.vending.AppMain;
import com.hethongviet.vending.Constant;
import com.hethongviet.vending.AppConfig;
import com.hethongviet.vending.R;
import com.hethongviet.vending.Utils;
import com.hethongviet.vending.helper.CodeResult;
import com.hethongviet.vending.helper.GeneralActivity;
import com.hethongviet.vending.helper.TimerOutUtils;
import com.hethongviet.vending.helper.db.BoxSQLite;
import com.hethongviet.vending.helper.dialog.DialogMessageBack;
import com.hethongviet.vending.helper.dialog.DialogMessageConfirm;
import com.hethongviet.vending.model.Box;
import com.hethongviet.vending.model.BoxItem;
import com.hethongviet.vending.model.Product;
import com.hethongviet.vending.model.Transaction;

public class ServiceModeActivity extends GeneralActivity
{
	private LinearLayout _listViewBox1 = null;
	private LinearLayout _listViewBox2 = null;
	private LinearLayout _listViewBox3 = null;

	private Button _buttonPageBack = null;
	private Button _buttonPageNext = null;
	private Button _buttonPageTemp = null;

	private Button _buttonServiceResetMachine = null;
	private Button _buttonServiceConfigMachine = null;

	private TimerOutUtils _timerOutUtils = null;

	private int _pageCurrent = 0;
	private int _totalPages = 0;

	private BoxSQLite _boxSqLite =  null;

	public ServiceModeActivity()
	{
		_boxSqLite = new BoxSQLite(this);
	}
	
	private static class ViewHolder
	{
		TextView textBoxName = null;
		TextView textProductName = null;
		TextView textProductAmount = null;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);

		/* Full screen */
		Utils.prepareWindow(this);

		setContentView(R.layout.page_service_mode);

		findViewById(R.id.button_back).setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View arg0)
			{
				showDialogCatch(R.string.message_exit_confirm_service);
			}
		});

		if (AppMain.getInstance().getCurrentAccount() == null) finish();

		try
		{
			TextView textViewUsername = (TextView) findViewById(R.id.text_user_name);
			//textViewUsername.setText(AppMain.getInstance()._accountCurrent.getName());
			textViewUsername.setVisibility(View.GONE);
		} catch (Exception e)
		{
			e.printStackTrace();
		}

		_listViewBox1 = (LinearLayout) findViewById(R.id.layout_list_box_1);
		_listViewBox2 = (LinearLayout) findViewById(R.id.layout_list_box_2);
		_listViewBox3 = (LinearLayout) findViewById(R.id.layout_list_box_3);

		_buttonPageBack = (Button) findViewById(R.id.button_page_back);
		_buttonPageNext = (Button) findViewById(R.id.button_page_next);
		_buttonPageTemp = (Button) findViewById(R.id.button_page_temp);

		_buttonServiceConfigMachine = (Button) findViewById(R.id.button_service_first_setup);
		_buttonServiceResetMachine = (Button) findViewById(R.id.button_service_reset);
		
		_buttonServiceResetMachine.setVisibility(View.GONE);

		_buttonServiceConfigMachine.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View arg0)
			{
				Intent intent = new Intent(ServiceModeActivity.this,
						ConfigMachineActivity.class);
				startActivity(intent);
			}
		});

		_buttonServiceResetMachine.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View arg0)
			{
				showDialogCatch(R.string.message_service_confirm_reset);
			}
		});

		_buttonPageBack.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				_pageCurrent--;
				if (_pageCurrent < 0)
				{
					_pageCurrent = 0;
					_buttonPageBack.setVisibility(View.GONE);
					_buttonPageTemp.setVisibility(View.GONE);
				}
				else
				{
					_buttonPageNext.setVisibility(View.VISIBLE);
				}
				showBoxes();
			}
		});

		_buttonPageNext.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				_pageCurrent++;
				if (_pageCurrent == _totalPages)
				{
					_pageCurrent = _totalPages - 1;
					_buttonPageNext.setVisibility(View.GONE);
					_buttonPageTemp.setVisibility(View.GONE);
				}
				else
					_buttonPageBack.setVisibility(View.VISIBLE);
				showBoxes();
			}
		});

		_timerOutUtils = new TimerOutUtils(this, R.id.text_time, false);
	}

	@Override
	public void onWindowFocusChanged(boolean hasFocus)
	{
		switch (AppMain.getInstance().getCodeResult())
		{
			case TIME_OUT_NOT_OPERATOR:
				showDialogCatch(R.string.message_time_out_user_not_operating);

				break;
			case TIME_OUT_USER:
				showDialogCatch(R.string.message_time_out_user);

				break;
			default:
				break;
		}

		AppMain.getInstance().setCodeResult(CodeResult.NONE);

		super.onWindowFocusChanged(hasFocus);
	}

	private void showDialogCatch(final int id)
	{
		runOnUiThread(new Runnable()
		{
			
			@Override
			public void run()
			{
				try
				{
					showDialog(id);
				} catch (Exception e)
				{
					e.printStackTrace();
				}
			}
		});
		
	}

	@Override
	protected Dialog onCreateDialog(int id)
	{
		if (id == R.string.message_exit_confirm_service)
		{
			return new DialogMessageConfirm(this, false, id, true, true);
		}
		else if (id == R.string.message_time_out_user)
		{
			return new DialogMessageBack(this, true, id, true);
		}
		else if (id == R.string.message_time_out_user_not_operating)
		{

			final DialogMessageConfirm dialogMessageConfirmNotOperating = new DialogMessageConfirm(
					this, false, id, true);
			OnClickListener onClickListenerYESNotOperating = new OnClickListener()
			{

				@Override
				public void onClick(View v)
				{
					dialogMessageConfirmNotOperating.cancel();
					_timerOutUtils.stopTimeOutDialog();
				}
			};
			dialogMessageConfirmNotOperating
					.setOnclickListenerYes(onClickListenerYESNotOperating);
			return dialogMessageConfirmNotOperating;
		}
		else if (id == R.string.message_service_confirm_reset)
		{

			final DialogMessageConfirm dialogMessageConfirmReset = new DialogMessageConfirm(
					this, false, id, false);
			OnClickListener onClickListenerYESReset = new OnClickListener()
			{

				@Override
				public void onClick(View v)
				{
					dialogMessageConfirmReset.cancel();
					resetAllBoxes();

					showBoxes();
				}
			};
			dialogMessageConfirmReset
					.setOnclickListenerYes(onClickListenerYESReset);
			return dialogMessageConfirmReset;
		}
		else
			return super.onCreateDialog(id);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event)
	{
		_timerOutUtils.startTimerNotOperating();

		return super.onTouchEvent(event);
	}

	@Override
	protected void onPause()
	{
		_timerOutUtils.stop();

		super.onPause();
	}

	private void showBoxes()
	{
		AppMain.getInstance().updateListBoxItems();

		int totalBoxes = (AppMain.getInstance().getListBoxItems() != null) ? AppMain.getInstance().getListBoxItems()
				.size() : 0;
		_totalPages = (totalBoxes != 0 && totalBoxes
				% Constant.MAX_VIEWS_A_PAGE == 0) ? (totalBoxes / Constant.MAX_VIEWS_A_PAGE)
				: (totalBoxes / Constant.MAX_VIEWS_A_PAGE + 1);

		if (totalBoxes == 0)
		{
			_listViewBox1.setVisibility(View.GONE);
			_listViewBox2.setVisibility(View.GONE);
			_listViewBox3.setVisibility(View.GONE);
			_buttonPageBack.setVisibility(View.GONE);
			_buttonPageNext.setVisibility(View.GONE);
		}
		else
		{
			_listViewBox1.setVisibility(View.VISIBLE);
			_listViewBox1.removeAllViews();
			_listViewBox2.setVisibility(View.VISIBLE);
			_listViewBox2.removeAllViews();
			_listViewBox3.setVisibility(View.VISIBLE);
			_listViewBox3.removeAllViews();

			final int startIndex = _pageCurrent * Constant.MAX_VIEWS_A_PAGE;
			final int endIndex = (_pageCurrent == _totalPages - 1) ? totalBoxes
					: (startIndex + Constant.MAX_VIEWS_A_PAGE);

			Utils.debug("start index = " + startIndex + " end index = "
					+ endIndex);

			final LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

			for (int index = startIndex; index < endIndex; index++)
			{
				final ViewHolder viewHolder = new ViewHolder();
				final View view = layoutInflater.inflate(
						R.layout.layout_one_box, null);

				viewHolder.textBoxName = (TextView) view
						.findViewById(R.id.text_box_name);
				viewHolder.textProductName = (TextView) view
						.findViewById(R.id.text_product_name);
				viewHolder.textProductAmount = (TextView) view
						.findViewById(R.id.text_product_amount);

				final BoxItem boxItem = AppMain.getInstance().getListBoxItems().get(index);
				viewHolder.textBoxName.setText(getString(R.string.box) + " "
						+ (index + 1));

				Product product = boxItem.getProduct();
				if (product != null)
				{
					viewHolder.textProductName.setText(product.getName());
					viewHolder.textProductAmount.setText(boxItem.getBox()
							.getProductAmount() + "");
				}
				else
				{
					viewHolder.textProductName.setVisibility(View.GONE);
					viewHolder.textProductAmount.setVisibility(View.GONE);
				}

				final int indexFinal = index;
				((LinearLayout) view.findViewById(R.id.layout_box_one))
						.setOnClickListener(new OnClickListener()
						{

							@Override
							public void onClick(View arg0)
							{
								AppMain.getInstance().setCurrentBoxItemIndex(indexFinal);

								Intent intent = new Intent(
										ServiceModeActivity.this,
										DetailBoxActivity.class);
								startActivity(intent);
							}
						});

				if (index - startIndex < Constant.MAX_VIEWS_A_COLUMN)
				{
					_listViewBox1.addView(view);
				}
				else if (index - startIndex < (Constant.MAX_VIEWS_A_COLUMN << 1))
				{
					_listViewBox2.addView(view);
				}
				else
					_listViewBox3.addView(view);

			}

		}

		if (_pageCurrent == 0 || _totalPages == 1)
		{
			_buttonPageBack.setVisibility(View.GONE);
			_buttonPageTemp.setVisibility(View.GONE);
		}
		if (_pageCurrent == _totalPages - 1 || _totalPages == 1)
		{
			_buttonPageNext.setVisibility(View.GONE);
			_buttonPageTemp.setVisibility(View.GONE);
		}

		if (_buttonPageBack.getVisibility() == View.VISIBLE
				&& _buttonPageNext.getVisibility() == View.VISIBLE) _buttonPageTemp
				.setVisibility(View.INVISIBLE);
	}

	private void resetAllBoxes()
	{
		for (BoxItem boxItem : AppMain.getInstance().getListBoxItems())
		{
			if (boxItem.getProduct() != null)
			{
				boxItem.setProduct(null);

				boxItem.getBox().setProductAmount(0);
				boxItem.getBox().setProductCode("");

				Box box = boxItem.getBox();

				_boxSqLite.insert(box);
			}
		}
	}

	@Override
	public void onAttachedToWindow()
	{
		if (AppConfig.USE_ATTACH_WINDOW_FOR_DISABLE_HOME_KEY)
		{
			this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
			super.onAttachedToWindow();
		}
	}

	@Override
	public boolean dispatchKeyEvent(KeyEvent event)
	{
		if (KeyEvent.KEYCODE_MENU == event.getKeyCode()
				|| KeyEvent.KEYCODE_DPAD_LEFT == event.getKeyCode()
				|| KeyEvent.KEYCODE_DPAD_DOWN == event.getKeyCode()
				|| KeyEvent.KEYCODE_DPAD_RIGHT == event.getKeyCode()
				|| KeyEvent.KEYCODE_DPAD_UP == event.getKeyCode()
				|| KeyEvent.KEYCODE_DPAD_CENTER == event.getKeyCode()
				|| KeyEvent.KEYCODE_CALL == event.getKeyCode()
				|| KeyEvent.KEYCODE_CAMERA == event.getKeyCode()
				|| KeyEvent.KEYCODE_ENDCALL == event.getKeyCode()
				|| KeyEvent.KEYCODE_HOME == event.getKeyCode()
				|| KeyEvent.KEYCODE_SEARCH == event.getKeyCode()
				|| KeyEvent.KEYCODE_BACK == event.getKeyCode())
		{
			return Utils.disableAllKey(event);
		}
		else
			return super.dispatchKeyEvent(event);

	}

//	@Override
//	public void onAttachedToWindow()
//	{
//		this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
//		super.onAttachedToWindow();
//	}

	@Override
	protected void onResume()
	{
		super.onResume();

		if (AppMain.getInstance().getNumberActivityFinishLogout() > 0)
		{
			AppMain.getInstance().setNumberActivityFinishLogout(AppMain.getInstance().getNumberActivityFinishLogout() - 1);
			finish();
			return;
		}

		_timerOutUtils.startTimerNotOperating();
		_timerOutUtils.startTimerOutUser();
		showBoxes();

	}

	@Override
	protected void onDestroy()
	{
		System.gc();
		super.onDestroy();
	}

	@Override
	public void onConnectFail(int typeError)
	{
	}

	@Override
	public void onNetworkMessageIncomming(Transaction transaction)
	{
	}

}
